#include "pch.h"
#include "BlurEffect.h"

using namespace Dx;
using namespace XamlFx;
using namespace Windows::UI::Xaml;
using namespace Windows::Graphics::Display;

DEPENDENCY_PROPERTY_IMP_ONCHANGE(BlurEffect, Radius, double, 5.0, OnBlurChanged)

BlurEffect::BlurEffect()
{
    SetPadding();
}

BlurEffect::~BlurEffect()
{
}

void BlurEffect::OnBlurChanged(DependencyObject^ d, DependencyPropertyChangedEventArgs^ e)
{
    auto blurEffect = safe_cast<BlurEffect^>(d);
    auto radius     = static_cast<float>(safe_cast<double>(e->NewValue));

    if (blurEffect->m_effect)
    {
        blurEffect->SetPadding();
        blurEffect->m_effect->SetValue(D2D1_GAUSSIANBLUR_PROP_STANDARD_DEVIATION, radius);
        blurEffect->Invalidate();
    }
}

void BlurEffect::SetPadding()
{
    float padding = (static_cast<float>(Radius) * 12.0f ) / 4.0f;

    Padding = Thickness(padding, padding, padding, padding);
}

auto BlurEffect::GetEffect(d2d::Bitmap const& input) -> d2d::Effect
{
    m_effect->SetInput(0, input.Get(), 0);

    return m_effect;
}

void BlurEffect::OnInitialized()
{
    m_effect = CreateEffect(CLSID_D2D1GaussianBlur);

    float blur = static_cast<float>(Radius);
    m_effect->SetValue(D2D1_GAUSSIANBLUR_PROP_STANDARD_DEVIATION, blur);
    m_effect->SetValue(D2D1_GAUSSIANBLUR_PROP_BORDER_MODE,        D2D1_BORDER_MODE_SOFT);
}